package com.realshare.frame.util.safety.america;

import com.realshare.frame.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Created by 曹传喜 on 2016/10/27.
 * MD5  单向加密器
 */

public class MD5Utils {
    private static final String ALGORITHM = "MD5";
    /**
     * 默认的密码字符串组合，用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
     */
    private static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 返回MD5单向加密后的十六进制字符串
     *
     * @param data 加密数据
     * @return 返回加密结果
     */
    public static String encrypt(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
            return StringUtils.parseByteArray2HexStr(messageDigest.digest(data.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getFileMD5(File file) {
        try {
            MessageDigest messagedigest = MessageDigest.getInstance(ALGORITHM);
            InputStream fis;
            fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = fis.read(buffer)) > 0) {
                messagedigest.update(buffer, 0, numRead);
            }
            fis.close();
            return bufferToHex(messagedigest.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, bytes.length);
    }

    private static String bufferToHex(byte[] bytes, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        for (int l = 0; l < n; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换
        // 为逻辑右移，将符号位一起右移,此处未发现两种符号有何不同
        char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }

    public static void main(String[] args) {
        System.out.println("加密文件的MD5值：" + getFileMD5(new File("D:\\md5.txt")));

        Date date = new Date();
        String source = "一醉汉不慎从三楼掉下，引来路人围观，一警察过来：发生了什么事？醉汉：不清楚，我也是刚到！";
        System.out.println("原文字：" + source);
        String encryptStr = encrypt(source);
        System.out.println("md5加密后：" + encryptStr);
        System.out.println("加密耗时：" + (new Date().getTime() - date.getTime()) + "毫秒");
    }
}
